/**
 * 关键词结果接口
 * @property word - 关键词内容
 * @property frequency - 关键词出现频率
 */
interface KeywordResult {
  word: string;
  frequency: number;
}

/**
 * 中文分词器类
 * 提供中文文本分词和停用词过滤功能
 */
class ChineseSegmenter {
  // 停用词集合
  private readonly stopWords: Set<string>;

  constructor() {
    // 常见停用词
    this.stopWords = new Set([
      "的",
      "了",
      "在",
      "是",
      "我",
      "有",
      "和",
      "就",
      "不",
      "人",
      "都",
      "一",
      "一个",
      "上",
      "也",
      "很",
      "到",
      "说",
      "要",
      "去",
      "你",
      "会",
      "着",
      "没有",
      "看",
      "好",
      "自己",
      "这",
      "那",
      "得",
      "里",
      "来",
      "把",
      "又",
      "这",
      "那",
      "着",
      "看",
      "等",
      "与",
      "对",
      "而",
      "中",
      "之",
      "或",
      "及",
      "并",
      "且",
    ]);
  }

  /**
   * 中文文本分词方法
   * @param text - 待分词的文本
   * @returns 分词后的词语数组
   */
  public segment(text: string): string[] {
    if (!text?.length) return [];

    const words: string[] = [];
    let currentWord = "";

    // 遍历文本字符进行分词
    for (const char of text) {
      // 如果是中文字符或数字，加入当前词
      if (this.isChinese(char) || this.isDigit(char)) {
        currentWord += char;
      } else if (currentWord) {
        // 遇到非中文字符且当前词不为空，完成一个词的分词
        words.push(currentWord);
        currentWord = "";
      }
    }

    // 添加最后一个词
    if (currentWord) words.push(currentWord);
    return words;
  }

  /**
   * 判断字符是否为中文
   * @param char - 待判断的字符
   * @returns 是否为中文字符
   */
  private isChinese(char: string): boolean {
    const charCode = char.charCodeAt(0);
    // 中文字符的Unicode范围
    return charCode >= 0x4e00 && charCode <= 0x9fff;
  }

  /**
   * 判断字符是否为数字
   * @param char - 待判断的字符
   * @returns 是否为数字字符
   */
  private isDigit(char: string): boolean {
    return /^\d$/.test(char);
  }
}

/**
 * 中文关键词提取函数
 * @param text - 输入文本
 * @param count - 返回关键词数量 (默认10)
 * @param minLength - 关键词最小长度 (默认2)
 * @returns 关键词数组
 */
export function extractKeywords(
  text: string,
  count = 10,
  minLength = 2
): string[] {
  const segmenter = new ChineseSegmenter();
  // 1. 对文本进行分词
  const words = segmenter.segment(text);

  // 2. 过滤停用词和短词
  const filteredWords = words.filter(
    word => word.length >= minLength
    // word => word.length >= minLength && !segmenter.stopWords.has(word)
  );

  // 3. 统计词频
  const freqMap: Record<string, number> = {};
  filteredWords.forEach(word => {
    freqMap[word] = (freqMap[word] || 0) + 1;
  });

  // 4. 排序并返回指定数量的关键词
  return Object.entries(freqMap)
    .map(([word, frequency]) => ({ word, frequency }))
    .sort((a, b) => b.frequency - a.frequency) // 按频率降序排序
    .slice(0, count) // 取前N个关键词
    .map(item => item.word); // 只返回关键词内容
}